package com.example.zjhuojback.controller;

import com.example.zjhuojback.common.Result;
import com.example.zjhuojback.entity.Forum;
import com.example.zjhuojback.entity.User;
import com.example.zjhuojback.service.ForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/forum")
public class ForumController {
    @Autowired
    private ForumService forumService;

    // 分页获取
    @GetMapping("/selectAll")
    public Result selectAll(int page, int size) {
        List<Forum> forumList = forumService.selectAll(page, size);
        long totalElements = forumService.countAll();  // 获取总记录数
        long totalPages = (totalElements + size - 1) / size;  // 计算总页数
        return Result.success(forumList, totalPages);
    }

    @GetMapping("/selectById")
    public Result selectById(Integer id) {
        Forum forum = forumService.selectById(id);
        List<Forum> forumList = forumService.getCommentsByPostId(id);
        return Result.success(forum, forumList);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Forum forum) {
        try {
            forumService.insertForum(forum);
        } catch (Exception e) {
            return Result.error("插入数据错误");
        }
        return Result.success();
    }
    @PostMapping("/addcomment")
    public Result addcomment(@RequestBody Forum forum) {
        try {
            forumService.addcomment(forum);
        } catch (Exception e) {
            return Result.error("插入数据错误");
        }
        return Result.success();
    }
    /*删除评论*/
    @DeleteMapping("deleteComment/{id}")
    public Result deleteComment(@PathVariable Integer id) {
        forumService.deleteComment(id);
        return Result.success();
    }

    /*删除帖子*/
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable Integer id) {
        forumService.delete(id);
        return Result.success();
    }

    /*更新帖子*/
    @PutMapping ("/update")
    public Result updata(@RequestBody Forum forum) {
        forumService.updataForum(forum);
        return Result.success();
    }

    /*点赞*/
    @PutMapping("/thumb/{id}")
    public Result updateThumbNum(@PathVariable Integer id) {
        forumService.incrementThumbNumById(id); // 调用服务方法增加点赞数
        return Result.success(); // 返回成功的响应
    }

    /*收藏*/
    @PutMapping("/favour/{id}")
    public Result updateFavourNumById(@PathVariable Integer id) {
        forumService.incrementFavourNumById(id); // 调用服务方法增加点赞数
        return Result.success(); // 返回成功的响应
    }

}
